package com.moehu.back.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.moehu.back.dao.DynamicDao;
import com.moehu.back.dao.OpusDao;
import com.moehu.back.model.*;
import com.moehu.back.model.expand.DynamiciImgModel;
import com.moehu.back.model.request.DynamicPushModel;
import com.moehu.back.model.response.UserInfoResponseModel;
import com.moehu.back.service.DynamicService;
import com.moehu.back.service.TokenService;
import com.moehu.back.utils.ResultUtils;
import com.moehu.back.utils.Tool;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class DynamicServiceImpl implements DynamicService {

    @Autowired
    DynamicDao dynamicDao;

    @Autowired
    OpusDao opusDao;

    @Autowired
    TokenService tokenService;

    @Override
    public ResultModel addDynamic(DynamicPushModel dynamic) {
        dynamic.setUser_id(tokenService.uid());
        dynamic.setDynamic_introduce(dynamic.getDynamic_introduce());
        Integer dynamicid = dynamicDao.addOrdinaryDynamic(dynamic);

        if (dynamicid == 1) {
            String[] imgArr = dynamic.getDynamic_imgs();
            List<ImgModel> imgs = new ArrayList<>();
            for(String url:imgArr) {
                ImgModel imgList = new ImgModel();
                imgList.setImg_url(url);
                imgList.setDynamic_id(dynamic.getDynamic_id());
                imgList.setUser_id(dynamic.getUser_id());
                imgs.add(imgList);
            }
            dynamicDao.DynamicCreatedImg(imgs);
            return ResultUtils.SuccessStatus("动态发布成功");
        } else {
            return ResultUtils.Error("动态发布失败");

        }
    }

    @Override
    public ResultModel personalDynamic(PagingModel dynamic) {
        dynamic.setUserid(dynamic.getUserid());
        // 分页处理
        Page page = PageHelper.startPage(dynamic.getPage(), dynamic.getCount());
        // 根据用户的id查询用户发布的动态
        List<DynamicModel> list = dynamicDao.getPersonalDynamic(dynamic);
        list = this.SetDynamicImg(list);
        return list.isEmpty() ? ResultUtils.Error("没有数据") : ResultUtils.Success(Tool.CountPage(page, list));
    }

    @Override
    public ResultModel TabsDynamic(PagingModel dynamic) {
        dynamic.setUserid(tokenService.uid());

        log.info("============ {}", dynamic.getUserid());
        // 分页处理
        Page page = PageHelper.startPage(dynamic.getPage(), dynamic.getCount());
        // 根据用户的id查询用户自己发布的动态
        List<DynamicModel> list = dynamicDao.getPersonalDynamic(dynamic);

        log.info("list.size ======= {}: ", list.size());

        // 拿用户 user_id 到关注表中查询 用户所关注 的 用户的id
        List<Integer> userToId = opusDao.getUserFollowId(dynamic.getUserid());
        log.info("userToId ======= {}: ", userToId);
        if (userToId.isEmpty()) {
            log.info("没有关注用户");
        } else {
            // 使用被关注用户user_id 查询他所发布的动态
            List<DynamicModel> FollowOpus = dynamicDao.getFollowUserDynamic(userToId);
            log.info("FollowOpus ======= {}: ", FollowOpus);
            for (DynamicModel foll: FollowOpus) {
                list.add(foll);
            }
        }

        list = this.SetDynamicImg(list);

        return list.isEmpty() ? ResultUtils.Error("没有数据") : ResultUtils.Success(Tool.CountPage(page, list));
    }

    public List<DynamicModel> SetDynamicImg(List<DynamicModel> list) {
        for(DynamicModel dy: list ) {
            // 获取发布该动态的用户信息
            dy.setUser_info(dynamicDao.getUserInfo(dy.getUser_id()));
            log.info("获取发布该动态的用户信息 === {}: ", dy.getDynamic_type());

            // 1 投稿动态，拿到作品id，去作品表查询，作品的主图然后作为动态的封面图
            if (dy.getDynamic_type() == 1) {
                Map url = dynamicDao.getMainImg(dy.getOpus_id());
                log.info("url============ {}", url);
                dy.setDynamic_img((String) url.get("opus_img"));
                log.info("投稿动态 主图地址 ==== {}：", url.get("opus_img"));

                // 0 普通动态，拿动态id到图片表查询，拿到一条记录，作为主图地址
            } else {
                ImgModel img = dynamicDao.getDynamicImg(dy.getDynamic_id());
                log.info("普通动态 主图地址 ==== {}：", img);
                if (img == null) {
                    dy.setDynamic_img("");
                } else {
                    dy.setDynamic_img(img.getImg_url());
                }
            }
        }

        return list;
    }

    @Override
    public ResultModel dynamicInfo(Integer dynamic_id) {
        // 查询动态主要信息
        DynamiciImgModel dy = dynamicDao.DynamicInfo(dynamic_id);
        if (dy != null) {
            // 查找动态的图片数组
            dy.setDynamic_imgs(dynamicDao.selectDynamicImgList(dynamic_id));
            // 查询动态用户信息
            dy.setUser_info(dynamicDao.getUserInfo(dy.getUser_id()));
            return ResultUtils.Success(dy);
        } else {
            return ResultUtils.Error("没有数据~");
        }
    }

    @Override
    public ResultModel recordHistory(Integer user_to_id) {
        if (tokenService.uid() != user_to_id) {
            Integer insId = dynamicDao.recordHistoryDao(tokenService.uid(), user_to_id);
            log.info("插入 insId ======= {}", insId);
            if (insId == 1) {
                return ResultUtils.SuccessStatus("记录成功");
            } else {
                return ResultUtils.SuccessStatus("已记录过，无需重复记录");
            }
        } else {
            return ResultUtils.SuccessStatus("不能记录自己查看自己");
        }

    }

    @Override
    public ResultModel getDynamicHistory(Integer pageNum, Integer count) {
        // 使用user_id 去查询用户访问了哪些其他用户的 user_id
        // 分页处理
        Page page = PageHelper.startPage(pageNum, count);
        List<Integer> UserToId = dynamicDao.getUserHistory(tokenService.uid());
        // 使用 user_id 去找访问记录中的用户信息
        List<UserInfoResponseModel> userList = new ArrayList<UserInfoResponseModel>();
        for (Integer e: UserToId) {
            UserInfoResponseModel UserOne = dynamicDao.getUserInfo(e);
            userList.add(UserOne);
        }

        return userList.isEmpty() ? ResultUtils.Error("没有数据") : ResultUtils.Success(Tool.CountPage(page, userList));
    }
}
